// 数据库操作
const mongoose = require('mongoose');
// 模型规则类
const {
	Schema
} = mongoose;
// 对象规则验证
const Joi = require('joi');

// 用户集合规则
const UserSchema = new Schema({
	// 昵称
	nickname: {
		type: String,
		required: true,
		minlength: 2,
		maxlength: 16
	},
	// 真名
	realName: {
		type: String,
		minlength: 1,
		maxlength: 20,
		default: 'Baby Panda'
	},
	// 账号
	account: {
		type: String,
		required: true,
		unique: true,
		minlength: 4,
		maxlength: 16
	},
	// 密码
	password: {
		type: String,
		required: true
	},
	// secret
	motoPwd: {
		type: String,
		required: true,
		minlength: 3,
		maxlength: 20
	},
	// 角色
	role: {
		type: Schema.Types.ObjectId,
		ref: 'Role',
		default: null
	},
	// 头像
	avatar: {
		type: String,
		default: null
	},
	// 电话号码
	phone: {
		type: String,
		default: '1111001111 '
	},
	birth: {
		type: Date,
		default: new Date('2017-06-12')
	},
	// 创建时间
	createTime: {
		type: Date,
		default: Date.now
	},
	// 状态-是否启用
	status: {
		type: Boolean,
		required: true,
		default: false
	},
	isDeleted: {
		type: Boolean,
		required: true,
		default: false
	}
}, {
	versionKey: false
});

// 用户集合类
const User = mongoose.model('User', UserSchema);

// 注册数据格式校验
const validateUser = user => {
	// 定义对象验证规则
	const schema = {
		nickname: Joi.string().min(2).max(16).required().error(new Error('昵称长度为2-16位')),
		realName: Joi.string().min(1).max(20).required().error(new Error('真名长度为1-20位')),
		account: Joi.string().regex(/^[A-Za-z][A-Za-z\d_]{3,15}$/).required().error(new Error('账号格式不正确，仅可包含英文字母、数字和下划线，且必须以字母开头，长度为4~16位')),
		password: Joi.string().min(3).max(20).required().error(new Error('密码格式不正确，长度为3~20位'))
	};
	// 验证
	return Joi.validate(user, schema, {
		// 检测到所有错误
		abortEarly: false,
		// 允许对象包含被忽略的未知键
		allowUnknown: true
	});
}

// 登录数据格式校验
const validateLogin = user => {
	// 定义对象验证规则
	const schema = {
		account: Joi.string().regex(/^[A-Za-z][A-Za-z\d_]{3,15}$/).required().error(new Error('账号或密码错误')),
		password: Joi.string().min(3).max(20).required().error(new Error('账号或密码错误'))
	};
	// 验证
	return Joi.validate(user, schema, {
		// 检测到错误立即返回
		abortEarly: true
	});
}

const findUserByAccount = account => User.findOne({
	account
}).select(['-password', '-motoPwd']).populate('role');

const findUserByID = _id => User.findOne({
	_id
}).select(['-password', '-motoPwd']).populate('role');

// 导出对象
module.exports = {
	User,
	validateUser,
	validateLogin,
	findUserByAccount,
	findUserByID
};